# 百日行动线索收集系统 - 启动脚本
# PowerShell版本

param(
    [switch]$SeparateWindows,  # 是否在分离的窗口中启动
    [switch]$Background        # 是否在后台启动
)

# 设置控制台编码
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 设置错误处理
$ErrorActionPreference = "Stop"

Write-Host "===========================================" -ForegroundColor Green
Write-Host "   百日行动线索收集系统 - 启动脚本" -ForegroundColor Green  
Write-Host "===========================================" -ForegroundColor Green
Write-Host ""

# 检查Node.js是否安装
Write-Host "🔍 检查环境..." -ForegroundColor Yellow
try {
    $nodeVersion = node --version 2>$null
    Write-Host "✅ Node.js已安装: $nodeVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ 错误: 未找到Node.js，请先安装Node.js" -ForegroundColor Red
    Write-Host "   下载地址: https://nodejs.org/" -ForegroundColor White
    Read-Host "按任意键退出"
    exit 1
}

# 检查目录是否存在
if (-not (Test-Path "backend")) {
    Write-Host "❌ 错误: 未找到backend目录" -ForegroundColor Red
    Read-Host "按任意键退出"
    exit 1
}

if (-not (Test-Path "frontend")) {
    Write-Host "❌ 错误: 未找到frontend目录" -ForegroundColor Red
    Read-Host "按任意键退出"
    exit 1
}

Write-Host "✅ 项目目录检查完成" -ForegroundColor Green
Write-Host ""

# 设置环境变量
Write-Host "⚙️  设置环境变量..." -ForegroundColor Yellow
$env:DB_HOST = "localhost"
$env:DB_PORT = "3306"
$env:DB_USER = "root"
$env:DB_PASSWORD = "newhand"
$env:DB_NAME = "hunaction"
$env:PORT = "3001"
$env:NODE_ENV = "development"

Write-Host "✅ 数据库配置:" -ForegroundColor Green
Write-Host "   • 主机: $($env:DB_HOST)" -ForegroundColor White
Write-Host "   • 端口: $($env:DB_PORT)" -ForegroundColor White
Write-Host "   • 用户: $($env:DB_USER)" -ForegroundColor White
Write-Host "   • 密码: $($env:DB_PASSWORD)" -ForegroundColor White
Write-Host "   • 数据库: $($env:DB_NAME)" -ForegroundColor White
Write-Host "✅ 服务器端口: $($env:PORT)" -ForegroundColor Green
Write-Host ""

# 检查并安装Backend依赖
Write-Host "📦 检查Backend依赖..." -ForegroundColor Yellow
Push-Location "backend"
try {
    if (-not (Test-Path "node_modules")) {
        Write-Host "🔄 安装Backend依赖..." -ForegroundColor Yellow
        npm install
        Write-Host "✅ Backend依赖安装完成" -ForegroundColor Green
    } else {
        Write-Host "✅ Backend依赖已存在" -ForegroundColor Green
    }
} catch {
    Write-Host "❌ Backend依赖安装失败: $_" -ForegroundColor Red
    Pop-Location
    Read-Host "按任意键退出"
    exit 1
} finally {
    Pop-Location
}

# 检查并安装Frontend依赖
Write-Host "📦 检查Frontend依赖..." -ForegroundColor Yellow
Push-Location "frontend"
try {
    if (-not (Test-Path "node_modules")) {
        Write-Host "🔄 安装Frontend依赖..." -ForegroundColor Yellow
        npm install
        Write-Host "✅ Frontend依赖安装完成" -ForegroundColor Green
    } else {
        Write-Host "✅ Frontend依赖已存在" -ForegroundColor Green
    }
} catch {
    Write-Host "❌ Frontend依赖安装失败: $_" -ForegroundColor Red
    Pop-Location
    Read-Host "按任意键退出"
    exit 1
} finally {
    Pop-Location
}

Write-Host ""
Write-Host "🚀 启动服务..." -ForegroundColor Yellow

# 创建作业脚本块
$BackendScript = {
    param($rootPath)
    Set-Location "$rootPath\backend"
    $env:DB_HOST = "localhost"
    $env:DB_PORT = "3306"
    $env:DB_USER = "root"
    $env:DB_PASSWORD = "newhand"
    $env:DB_NAME = "hunaction"
    $env:PORT = "3001"
    $env:NODE_ENV = "development"
    
    Write-Host "🔗 启动Backend服务器 (端口: 3001)..." -ForegroundColor Blue
    node app.js
}

$FrontendScript = {
    param($rootPath)
    Set-Location "$rootPath\frontend"
    Write-Host "🌐 启动Frontend代理服务器 (端口: 8080)..." -ForegroundColor Blue
    npm start
}

$currentPath = Get-Location

if ($SeparateWindows) {
    # 在分离的窗口中启动
    Write-Host "🪟 在分离的窗口中启动服务..." -ForegroundColor Cyan
    
    # 启动Backend
    Start-Process powershell -ArgumentList "-NoExit", "-Command", "& { Set-Location '$currentPath\backend'; `$env:DB_HOST='localhost'; `$env:DB_PORT='3306'; `$env:DB_USER='root'; `$env:DB_PASSWORD='newhand'; `$env:DB_NAME='hunaction'; `$env:PORT='3001'; `$env:NODE_ENV='development'; Write-Host '🔗 Backend服务器启动中...' -ForegroundColor Blue; node app.js }"
    
    Start-Sleep -Seconds 2
    
    # 启动Frontend
    Start-Process powershell -ArgumentList "-NoExit", "-Command", "& { Set-Location '$currentPath\frontend'; Write-Host '🌐 Frontend服务器启动中...' -ForegroundColor Blue; npm start }"
    
    Write-Host ""
    Write-Host "✅ 服务已在分离的窗口中启动!" -ForegroundColor Green
    Write-Host "🔗 Backend: http://localhost:3001" -ForegroundColor White
    Write-Host "🌐 Frontend: http://localhost:8080" -ForegroundColor White
    Write-Host "📝 管理后台: http://localhost:3001/admin/login.html" -ForegroundColor White
    
} elseif ($Background) {
    # 在后台启动
    Write-Host "🔄 在后台启动服务..." -ForegroundColor Cyan
    
    # 后台启动Backend
    $backendJob = Start-Job -ScriptBlock $BackendScript -ArgumentList $currentPath -Name "Backend"
    
    Start-Sleep -Seconds 3
    
    # 后台启动Frontend  
    $frontendJob = Start-Job -ScriptBlock $FrontendScript -ArgumentList $currentPath -Name "Frontend"
    
    Write-Host ""
    Write-Host "✅ 服务已在后台启动!" -ForegroundColor Green
    Write-Host "🔗 Backend: http://localhost:3001" -ForegroundColor White
    Write-Host "🌐 Frontend: http://localhost:8080" -ForegroundColor White
    Write-Host "📝 管理后台: http://localhost:3001/admin/login.html" -ForegroundColor White
    Write-Host ""
    Write-Host "💡 使用以下命令管理后台作业:" -ForegroundColor Yellow
    Write-Host "   Get-Job                    # 查看作业状态" -ForegroundColor White
    Write-Host "   Receive-Job -Name Backend  # 查看Backend日志" -ForegroundColor White
    Write-Host "   Receive-Job -Name Frontend # 查看Frontend日志" -ForegroundColor White
    Write-Host "   Stop-Job -Name Backend     # 停止Backend" -ForegroundColor White
    Write-Host "   Stop-Job -Name Frontend    # 停止Frontend" -ForegroundColor White
    Write-Host "   Remove-Job -Name Backend   # 删除Backend作业" -ForegroundColor White
    Write-Host "   Remove-Job -Name Frontend  # 删除Frontend作业" -ForegroundColor White
    
} else {
    # 在当前窗口中启动（使用Start-Process后台运行）
    Write-Host "🔄 在当前会话中启动服务..." -ForegroundColor Cyan
    
    # 启动Backend进程
    Write-Host "🔗 启动Backend服务器..." -ForegroundColor Blue
    $backendProcess = Start-Process powershell -ArgumentList "-WindowStyle", "Minimized", "-Command", "& { Set-Location '$currentPath\backend'; `$env:DB_HOST='localhost'; `$env:DB_PORT='3306'; `$env:DB_USER='root'; `$env:DB_PASSWORD='newhand'; `$env:DB_NAME='hunaction'; `$env:PORT='3001'; `$env:NODE_ENV='development'; node app.js }" -PassThru
    
    Start-Sleep -Seconds 3
    
    # 启动Frontend进程
    Write-Host "🌐 启动Frontend服务器..." -ForegroundColor Blue
    $frontendProcess = Start-Process powershell -ArgumentList "-WindowStyle", "Minimized", "-Command", "& { Set-Location '$currentPath\frontend'; npm start }" -PassThru
    
    Start-Sleep -Seconds 2
    
    Write-Host ""
    Write-Host "✅ 系统启动完成!" -ForegroundColor Green
    Write-Host "===========================================" -ForegroundColor Green
    Write-Host "🔗 Backend API: http://localhost:3001" -ForegroundColor White
    Write-Host "🌐 Frontend: http://localhost:8080" -ForegroundColor White
    Write-Host "📝 管理后台: http://localhost:3001/admin/login.html" -ForegroundColor White
    Write-Host "📊 线索提交: http://localhost:8080/submit.html" -ForegroundColor White
    Write-Host "===========================================" -ForegroundColor Green
    Write-Host ""
    Write-Host "💡 按 Ctrl+C 或关闭此窗口来停止服务" -ForegroundColor Yellow
    Write-Host "📋 进程ID - Backend: $($backendProcess.Id), Frontend: $($frontendProcess.Id)" -ForegroundColor Gray
    
    # 等待用户中断
    try {
        Write-Host "⏳ 服务运行中... (按 Ctrl+C 停止)" -ForegroundColor Yellow
        while ($true) {
            Start-Sleep -Seconds 5
            
            # 检查进程是否还在运行
            $backendRunning = Get-Process -Id $backendProcess.Id -ErrorAction SilentlyContinue
            $frontendRunning = Get-Process -Id $frontendProcess.Id -ErrorAction SilentlyContinue
            
            if (-not $backendRunning) {
                Write-Host "⚠️  Backend进程已停止" -ForegroundColor Yellow
            }
            if (-not $frontendRunning) {
                Write-Host "⚠️  Frontend进程已停止" -ForegroundColor Yellow
            }
            
            if (-not $backendRunning -and -not $frontendRunning) {
                Write-Host "❌ 所有服务都已停止" -ForegroundColor Red
                break
            }
        }
    } catch [System.Management.Automation.CommandInterruptedException] {
        Write-Host ""
        Write-Host "🛑 收到停止信号，正在关闭服务..." -ForegroundColor Yellow
        
        # 停止进程
        if (Get-Process -Id $backendProcess.Id -ErrorAction SilentlyContinue) {
            Stop-Process -Id $backendProcess.Id -Force
            Write-Host "✅ Backend服务已停止" -ForegroundColor Green
        }
        if (Get-Process -Id $frontendProcess.Id -ErrorAction SilentlyContinue) {
            Stop-Process -Id $frontendProcess.Id -Force
            Write-Host "✅ Frontend服务已停止" -ForegroundColor Green
        }
    }
}

Write-Host ""
Write-Host "===========================================" -ForegroundColor Green
Write-Host "   感谢使用百日行动线索收集系统" -ForegroundColor Green
Write-Host "===========================================" -ForegroundColor Green 